package com.zjlanyun.eplus.view.report.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.yanzhenjie.nohttp.rest.Response;
import com.zjlanyun.eplus.R;
import com.zjlanyun.eplus.network.WebApi;
import com.zjlanyun.eplus.nohttp.HttpRequest;
import com.zjlanyun.eplus.nohttp.SimpleHttpListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.listener.ColumnChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.ColumnChartView;

import static com.zjlanyun.eplus.view.report.UtilConstants.ACTION;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_ACTION;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_HF_XVALUE;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_HF_YVALUE;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_JSON_DATA;
import static com.zjlanyun.eplus.view.report.UtilConstants.MODEL_ID;
import static com.zjlanyun.eplus.view.report.UtilConstants.SHOW_HISTOGRM;
import static com.zjlanyun.eplus.view.report.UtilConstants.SQL_CONDITION;
/**
 * 作者：韩笑 on 2017/6/23 0023 16:20
 * <p>
 * 作用：柱状统计图界面
 */


public class HistogrmFragment extends Fragment{
    private static final String TAG = "HistogrmFragment";
    //模型id
    private String modelId = "";
    //统计图相关
    private ColumnChartView chart;
    private ColumnChartData data;
    private List<AxisValue> axisValues;
    private List<Column> columns;
    //X轴数组
    public String[] months;
    //查询获得的数据list
    private List<Map<String,String>> mList ;
    public static HistogrmFragment newInstance(String modelId, String sql) {
        Bundle args = new Bundle();
        HistogrmFragment fragment = new HistogrmFragment();
        args.putString(MODEL_ID, modelId);
        args.putString(SQL_CONDITION, sql);
        fragment.setArguments(args);
        return fragment;
    }
    Handler myHandle = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SHOW_HISTOGRM:
                    setChartDate();
                    break;
                default:

                    break;
            }
        }
    };
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.histogrm_fragment, null);
        Log.d(TAG, getArguments().getString(MODEL_ID) + "/" + getArguments().getString(SQL_CONDITION));
        initView(view);
        return view;
    }
    /**
    *初始化
    *@author xiao.han
    *created at 2017/6/23 0023 16:48
    */
    public void initView(View v) {
        modelId = getArguments().getString(MODEL_ID);
        chart = (ColumnChartView) v.findViewById(R.id.chart);
        Log.d(TAG,"操作：" + ACTION + ".MODEL_ID:"+modelId);
        initData(ACTION,modelId);
    }

    /**
     * 获取数据
     * @param arg0 操作
     * @param arg1 模型id
     */
    public void initData(String arg0 ,String arg1){
        mList = new ArrayList<>();
        HttpRequest client = new HttpRequest(getActivity(), WebApi.api());
        client.getRequest().add(KEY_ACTION, arg0);
        client.getRequest().add(MODEL_ID, arg1);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                super.onSucceed(what, response);
                Log.d(TAG,"返回的数据:"+response.get().toString());
                try {
                    mList = new ArrayList<Map<String, String>>();
                    JSONObject jsonObject = new JSONObject(response.get().toString());
                    JSONArray jsonArray = jsonObject.getJSONArray(KEY_JSON_DATA);
                    for (int i = 0; i < jsonArray.length(); i ++){
                        JSONObject myjsonObject = (JSONObject) jsonArray.get(i);
                        Map<String,String> map = new HashMap<String, String>();
                        map.put(KEY_HF_XVALUE,myjsonObject.optString(KEY_HF_XVALUE));
                        map.put(KEY_HF_YVALUE,myjsonObject.optString(KEY_HF_YVALUE));
                        mList.add(map);
                    }
                    myHandle.sendEmptyMessage(SHOW_HISTOGRM);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
    *将list置入柱状统计图中
    *@author xiao.han
    *created at 2017/6/23 0023 16:49
    */
    public void setChartDate() {
        chart.setOnValueTouchListener(new ValueTouchListener());
        columns = new ArrayList<Column>();
        axisValues = new ArrayList<AxisValue>();
        months = new String[mList.size()];
        for (int i = 0; i < mList.size(); i++) {
            months[i] = mList.get(i).get(KEY_HF_XVALUE);
        }
        //向图表中置入数据
        for (int i = 0; i < months.length; i++) {
            List<SubcolumnValue> values = new ArrayList<SubcolumnValue>();
            values.add(new SubcolumnValue(Integer.parseInt(mList.get(i).get(KEY_HF_YVALUE)), ChartUtils.pickColor()));
            Column column = new Column(values);
            axisValues.add(new AxisValue(i).setLabel(months[i]));
            columns.add(column.setHasLabelsOnlyForSelected(true));
            column.setHasLabels(true);// 是否显示节点数据
        }
        data = new ColumnChartData(columns);
        data.setAxisXBottom(new Axis(axisValues).setHasLines(true));
        chart.setValueSelectionEnabled(true);
        chart.setZoomType(ZoomType.HORIZONTAL);
        Viewport v = new Viewport(0, 110, 6, 0);
        chart.setMaximumViewport(v);
        chart.setCurrentViewport(v);

        Axis axisY = new Axis().setHasLines(true);
        data.setAxisYLeft(axisY);
        axisY.setValues(null);
        chart.setColumnChartData(data);
    }

    /**
    *柱状统计图监听
    *@author xiao.han
    *created at 2017/6/23 0023 16:50
    */
    private class ValueTouchListener implements ColumnChartOnValueSelectListener {
        @Override
        public void onValueSelected(int columnIndex, int subcolumnIndex, SubcolumnValue value) {
            Toast.makeText(getActivity(), months[columnIndex] + ":  ￥" + value.getValue() + "元", Toast.LENGTH_SHORT).show();
            //  Log.d(TAG, "columnIndex:" + columnIndex + "Selected: " + value.getValue());

        }
        @Override
        public void onValueDeselected() {
            // TODO Auto-generated method stub
        }
    }

}
